import pymysql


class DButil:
    __conn = None
    __curs = None

    @classmethod
    def __get_conn(cls):
        h = "211.103.136.244"
        p = 7061
        u = "student"
        pw = "iHRM_student_2021"
        db = "ihrm"
        chset = "utf8"

        cls.__conn = pymysql.connect(host=h, port=p, user=u, password=pw,
                                     database=db, charset=chset)
        return cls.__conn

    @classmethod
    def __get_cursor(cls):
        cls.__curs=cls.__get_conn().cursor()


    @classmethod
    def __close_cursor(cls):
        cls.__curs.close()

    @classmethod
    def __close_conn(cls):
        cls.__conn.close()

    @classmethod
    def sql_perform(cls, sql):
        cls.__get_cursor()
        try:
            if sql.split()[0].lower() == "select":
                cls.__curs.execute(sql)
                res = cls.__curs.fetchall()
                print("查询结果集===", res)
                return res
            else:
                cls.__curs.execute(sql)
                cls.__conn.commit()
                print("生效的行数===", cls.__conn.affected_rows())

        except Exception as e:
            print("err", e)
            if sql.split()[0].lower() != "select":
                cls.__conn.rollback()

        finally:
            cls.__close_cursor()
            cls.__close_conn()




